package org.example.yunshu.demos.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.example.yunshu.demos.constant.Constants;
import org.example.yunshu.demos.constant.HttpSessionNullException;
import org.example.yunshu.demos.model.Result;
import org.example.yunshu.demos.model.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession httpSession = request.getSession();
        if(httpSession == null){
            log.error("httpSession为null");
//           抛出异常
            throw new HttpSessionNullException("httpSession为null");
        }

        UserInfo userInfo = (UserInfo) httpSession.getAttribute(Constants.USERINFO_KEY);
        if(userInfo == null || userInfo.getUserId()<1) {
            response.setStatus(401);
            return false;
        }
        return true ;
    }

}

